﻿using System;
using System.Threading.Tasks;
using Furion.DatabaseAccessor;
using Newtonsoft.Json;

namespace Hu.Smart.Core.Messages
{
    public class MessageManager : IMessageManager
    {
        private readonly IRepository<Message> _messageRepository;

        public MessageManager(IRepository<Message> messageRepository)
        {
            _messageRepository = messageRepository;
        }

        public async Task CreateMqMessageAsync(string from, string to, string content, MqMessageParameter parameters, MessageDirection direction)
        {
            var message = new Message(from, to, MessageType.MQ.ToString())
            {
                Content = content,
                CustomData = JsonConvert.SerializeObject(parameters),
                Direction = direction.ToString()
            };
            await CreateMessage(message);
        }

        public async Task SendEmailAsync(string title, string content, string to, string from = null, string cc = null, string bcc = null)
        {
            var message = new Message(from, to, MessageType.Email.ToString())
            {
                CC = cc,
                BCC = bcc,
                Title = title,
                Content = content,
                Direction = MessageDirection.Out.ToString()
            };

            await CreateMessage(message);
        }

        async Task CreateMessage(Message message)
        {
            try
            {
                message.Status = 0;
                await _messageRepository.InsertAsync(message);
            }
            catch (Exception ex)
            {
                //Logger.Error("MessageManager-CreateMessage-ERROR", ex);
            }
        }
    }
}